var express = require('express');
var router = express.Router();

router.post('/postArticle', function(req, res, next) {
  if(!req.body.title || !req.body.slug || !req.body.text)
    return next(new Error("No article payload."));
  var article = {
    title: req.body.title,
    slug: req.body.slug,
    text: req.body.text,
    published: false
  };
  req.collections.articles.insert(article, function (err, resp) {
    if(err)
      return next(err);
    res.render('post',{error: '发布成功！切换到首页就能看到。'});
  });
});

router.get('/post', function(req, res, next) {
  res.render('post');
});

router.get('/:slug', function(req, res, next){
  if(!req.params.slug)
    return next(new Error("No article slug."));
  req.collections.articles.findOne({slug: req.params.slug}, function(err, doc){
    if(err) next(err);
    if(!doc.published) return res.sendStatus(401);
    res.render('article',doc);
  });
});

module.exports = router;

